package cbfg.rvadapter

import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.RecyclerView
import cbfg.rvadapter.state.RVState
import cbfg.rvadapter.state.RVStateFlags
import cbfg.rvadapter.state.RV_STATE_EMPTY

/**
 * @author: TomHawk
 * @description: 组合 adapter 封装，支持刷新、加载更多、空布局、错误布局等状态页
 * @date: 2025/6/30 14:29
 */
class RVConcatHelper private constructor(builder: Builder) {
    val concatAdapter = ConcatAdapter(builder.config, builder.adapters)
    private val refreshAdapter: RVAdapter<RVState>? = builder.refreshAdapter
    private val stateAdapter: RVAdapter<RVState>? = builder.stateAdapter

    /** 记录当前状态 */
    private var curState: RVState? = null

    init {
        if (stateAdapter != null) {
            concatAdapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
                override fun onChanged() {
                    //Log.d("aaaddd", "onChanged:${concatAdapter.itemCount}")
                    checkEmptyState()
                }

                override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
                    //Log.d("aaaddd", "onItemRangeInserted:${concatAdapter.itemCount}")
                    checkEmptyState()
                }

                override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
                    //Log.d("aaaddd", "onItemRangeRemoved:${concatAdapter.itemCount}")
                    checkEmptyState()
                }

                private fun checkEmptyState() {
                    if (!hasData) {
                        showState(RV_STATE_EMPTY)
                    } else if (curState?.state == RVStateFlags.EMPTY && concatAdapter.itemCount > 1) {
                        //有数据了的话移除空布局：
                        hideState()
                    }
                }
            })
        }
    }

    fun bind(rv: RecyclerView): RVConcatHelper {
        rv.adapter = concatAdapter
        return this
    }

    /**
     * 是否有数据
     */
    private val hasData: Boolean
        get() = concatAdapter.itemCount > 0

    /** 数据列表为空时是否自动显示空布局 */
    var enableShowEmptyState = false
        set(value) {
            field = value
            showState(RV_STATE_EMPTY)
        }

    /**
     * 显示状态页
     */
    fun showState(state: RVState) {
        if (state.state == RVStateFlags.EMPTY) {
            if (!hasData && enableShowEmptyState) {
                hideState()
                curState = state
                //Log.d("aaaddd", "showState empty:${concatAdapter.itemCount}")
                stateAdapter?.setItems(listOf(state))
                //Log.d("aaaddd", "showState empty2:${concatAdapter.itemCount}")
            }
        } else {
            hideState()
            curState = state
            if (state.state == RVStateFlags.REFRESHING) {
                //Log.d("aaaddd", "showState:refresh,$refreshAdapter")
                refreshAdapter?.setItems(listOf(state))
            } else {
                stateAdapter?.setItems(listOf(state))
            }
        }
    }

    fun hideState() {
        curState = null
        //需要判断数据不为空才能调用 clear，否则会调用到 notifyDataSetChanged 导致触发 onChanged 回调，导致死循环：
        refreshAdapter?.let { if (it.itemCount > 0) it.clear() }
        stateAdapter?.let { if (it.itemCount > 0) it.clear() }
    }

    class Builder {
        var config: ConcatAdapter.Config = ConcatAdapter.Config.DEFAULT
            private set
        var refreshAdapter: RVAdapter<RVState>? = null
            private set
        var stateAdapter: RVAdapter<RVState>? = null
            private set

        val adapters: MutableList<RVAdapter<*>> = mutableListOf()

        fun setConfig(config: ConcatAdapter.Config): Builder {
            this.config = config
            return this
        }

        /**
         * 添加刷新状态 adapter，如果调用多次，会记录最后一次作为刷新用途的 adapter。
         * 如果需要添加到头部，需要比其它 adapter 先添加。
         */
        fun addRefreshAdapter(adapter: RVAdapter<RVState>): Builder {
            refreshAdapter = adapter
            return addAdapter(adapter)
        }

        /**
         * 添加其它状态 adapter，如果调用多次，会记录最后一次作为状态用途的 adapter。
         * 如果需要添加到尾部，需要比其它 adapter 后添加。
         */
        fun addStateAdapter(adapter: RVAdapter<RVState>): Builder {
            stateAdapter = adapter
            return addAdapter(adapter)
        }

        /**
         * 添加普通数据 adapter
         */
        fun addAdapter(adapter: RVAdapter<*>): Builder {
            adapters.add(adapter)
            return this
        }

        fun build(): RVConcatHelper {
            return RVConcatHelper(this)
        }
    }
}